package com.tjf.skin_loading;

import static skin.support.widget.SkinCompatHelper.INVALID_ID;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import skin.support.content.res.SkinCompatResources;
import skin.support.widget.SkinCompatHelper;
import skin.support.widget.SkinCompatSupportable;

public class RatingBar extends View implements SkinCompatSupportable {

    private Bitmap mNormalBit;
    private Bitmap mFocusBit;
    private int mGradeNum;

    private int mCurrentGrade = 0;
    int normalBitId;
    int focusBitId;

    public RatingBar(Context context) {
        this(context, null);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);

        //不能直接获取资源bitmap，所以，先获取资源 ID ，再由 BitmapFactory 转换
        normalBitId = typedArray.getResourceId(R.styleable.RatingBar_normalBit, 0);
        if (normalBitId == 0) {
            throw new RuntimeException("请设置属性 normalBit");
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 1;
        mNormalBit = BitmapFactory.decodeResource(getResources(), normalBitId, opts);
        //不能直接获取资源bitmap，所以，先获取资源 ID ，再由 BitmapFactory 转换
        focusBitId = typedArray.getResourceId(R.styleable.RatingBar_focusBit, 0);
        if (focusBitId == 0) {
            throw new RuntimeException("请设置属性 focusBit");
        }
//        mFocusBit = BitmapFactory.decodeResource(getResources(), focusBitId, opts);
        appSkinBitmap();
        mGradeNum = typedArray.getInt(R.styleable.RatingBar_gradeNum, mGradeNum);

        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //高度 一张图片的高度 实现 padding 间隔自己根据 示意图 和下面 公式对着算
        int height = Math.max(mNormalBit.getHeight(),
                mFocusBit.getHeight()) + getPaddingTop() + getPaddingBottom();
        int width = Math.max(mNormalBit.getWidth(),
                mFocusBit.getWidth()) * mGradeNum + mGradeNum * (getPaddingLeft() + getPaddingRight());

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画触摸前的图片
        for (int i = 0; i < mGradeNum; i++) {
            float x1 = i * mNormalBit.getWidth() + (i + 1) * getPaddingLeft();
            //画触摸后的图片
            float x2 = i * mFocusBit.getWidth() + (i + 1) * getPaddingLeft();
            if (i < mCurrentGrade) {
                //画触摸后的图片
                canvas.drawBitmap(mFocusBit, x2, getPaddingTop(), null);
            } else {
                //画触摸前的图片
                canvas.drawBitmap(mNormalBit, x1, getPaddingTop(), null);
            }
        }
    }

    boolean isfirst = true;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        System.out.println("moveX -> " + event.getAction());
        //按下 移动 抬起 处理逻辑都一样，判断手指的位置，根据当前位置计算分数，再去刷新
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: //按下
            case MotionEvent.ACTION_MOVE: //移动
//            case MotionEvent.ACTION_UP: //抬起  优化，尽量减少onDraw()
            {
                float moveX = event.getX(); //event.getRawX()获取屏幕的x位置  event.getX()相当于控件的x位置
                System.out.println("moveX -> " + moveX);
                //计算分数
                int currentGrade = (int) (moveX / (mNormalBit.getWidth() + getPaddingLeft()));
                if (currentGrade <= 0.0f) {
                    currentGrade = 0;
                } else if (currentGrade > mGradeNum) {
                    currentGrade = mGradeNum;
                } else {
                    currentGrade += 1;
                }
                Log.i("dangiqna ==", "1=点击的item=" + currentGrade +
                        "--前一次的item-" + mCurrentGrade);
                if (currentGrade == mCurrentGrade) {
//                    if (!isfirst) {
//                        currentGrade--;
//                        mCurrentGrade = (int) currentGrade;
//
//                        Log.i("dangiqna ==", "2=点击的item=" + currentGrade +
//                                "--前一次的item-" + mCurrentGrade);
//                        invalidate();
//                    }
//                    isfirst = !isfirst;

                    return true;
                }


                mCurrentGrade = (int) currentGrade;
                invalidate(); //系统帮我们调用 onDraw() 减少onDraw()的调用 ， 目前是不断调用
            }
            break;
        }
        return true;//onTouch 后面会逐步讲源码 false 代表不消费 第一次 Down false DOWN以后的事件进不来
    }

    public void appSkinBitmap() {
        focusBitId = SkinCompatHelper.checkResourceId(focusBitId);
        if (focusBitId != INVALID_ID) {
            Drawable drawable = SkinCompatResources.getDrawable(getContext(), focusBitId);
            mFocusBit = ((BitmapDrawable) drawable).getBitmap();
        }
    }

    @Override
    public void applySkin() {
        appSkinBitmap();
    }
}